//获取应用实例
const app = getApp()
var inputVal = '';
var msgList = [];
var comtlost = new Array();
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
const plugin = requirePlugin('WechatSI');
function initData(that) {
  inputVal = '';

  msgList = [

    {
      speaker: 'server',
      contentType: 'text',
      content: '欢迎使用书海语音系统！',
    },
    {
      speaker: 'server',
      contentType: 'text',
      content: '   提示！！点击下方提示序号',
      comtlost: [{ problem: '织布鸟项目组张帆' },
      { problem: "蜂巢项目组张雪晨" },
      { problem: "探路者项目组麻树强" },
      { problem: "办公室李洋" },],
    },
  ]
  that.setData({
    msgList,
    inputVal
  })
}

Page({

  data: {

    dies: true,
    openRecordingdis: true,//录音图片的不同
    shutRecordingdis: false,//录音图片的不同
    recordingTimeqwe: 0,//录音计时
    setInter: "",//录音名称
    content: '哈哈哈reeb',//内容
    src: '', //
    scrollHeight: '100vh',
    inputBottom: 0,
    tishi: true,
    tartPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
    sendLock: true,
    recorderManager: wx.getRecorderManager(), //录音管理上下文    
    startPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
    sendLock: true, //发送锁，当为true时上锁，false时解锁发送

    flag: "" //遮罩
  },
  onLoad: function (options) {
    initData(this);


  },

  onReady(e) {
    //创建内部 audio 上下文 InnerAudioContext 对象。
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError(function (res) {
      console.log(res);
      wx.showToast({
        title: '语音播放失败',
        icon: 'none',
      })
    })
  },

  //录音计时器
  recordingTimer: function () {
    var that = this;
    //将计时器赋值给setInter
    that.data.setInter = setInterval(
      function () {
        var time = that.data.recordingTimeqwe + 1;
        that.setData({
          recordingTimeqwe: time
        })
      }
      , 1000);
  },

  //开始录音
  openRecording: function (e) {
    const recorderManager = wx.getRecorderManager()
    var that = this;
    console.log("手指按下了...")
    that.end()
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          shutRecordingdis: true,
          openRecordingdis: false
        })
      }
    })
    const options = {
      duration: 10000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
      sampleRate: 8000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 48000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    recorderManager.start(options)
    //开始录音计时   
    that.recordingTimer();
    //开始录音
    wx.showToast({
      title: "正在录音···",
      icon: "none",
      duration: 600000 //先定义个60秒，后面可以手动调用wx.hideToast()隐藏
    });
    recorderManager.onStart(() => {
      console.log('。。。开始录音。。。')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log("错误回调++++++++++" + res.errMsg);
      console.log("错误回调++++++++++" + JSON.stringify(res));
    })
  },

  //结束录音
  shutRecording: function () {
    wx.hideToast()
    console.log('手指离开了 。。')
    const recorderManager = wx.getRecorderManager()
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          shutRecordingdis: false,
          openRecordingdis: true,
        })
      }
    })
    //  recorderManager.onStop((res) => {  //监听录音停止的事件


    recorderManager.stop();
    var asd = wx.getStorageSync('shuhai_party_id')
    recorderManager.onStop((res) => {
      console.log(res.duration + "进入半段")
      if (res.duration < 1000) {

        console.log("进入半段")
        wx.showToast({
          icon: "none",
          title: "录音时间过短"
        })
        return;
      } else {
        wx.showToast({
          title: '正在上传',
          icon: 'loading',
          mask: true,
          duration: 60000,
        })
        console.log('。。停止录音临时路径 。。', res.tempFilePath)
        console.log('。。停止录音录音总时长。。', res.duration)
        console.log('。。停止录音录音文件大小。。', res.fileSize)
        const { tempFilePath } = res;
        //结束录音计时  
        clearInterval(that.data.setInter);
        console.log('。。停止录音。。', that.data.setInter),
          console.log('。。id。。', asd),
          //开启遮罩
          that.setData({
            flag: "mask"
          })
        //上传录音
        wx.uploadFile({
          url: 'https://gdzc.sxpmg.com/shuhai/wx_SubjectRecordKeeping.do',//这是你自己后台的连接
          filePath: tempFilePath,
          name: "file",//后台要绑定的名称
          header: {
            "Content-Type": "application/json"
          },
          success: function (res) {
            var json = JSON.parse(res.data)
            console.log(">>>>>>>>dfbgdfg dsgdfg >>" + res.data);
            console.log(">>>>>>>------->>>>>>>" + json.length);
            var jso = JSON.stringify(json)
            console.log(">>>>>>>------->>>>>>>" + jso);

            if (json.hp == "") {
              msgList.push({
                speaker: 'server',
                contentType: 'text',
                content: json.answer,
                // comtlost: jso,

              });
            } else {
              msgList.push({
                speaker: 'customer',
                contentType: 'text',
                content: json.hp,
              });
              msgList.push({
                speaker: 'server',
                contentType: 'text',
                content: json.answer,
                // comtlost: jso,       
              });

            }
            //发送消息提示音
            const innerAudioContext = wx.createInnerAudioContext();
            innerAudioContext.autoplay = true;
            innerAudioContext.src = "/audio/9675.mp3"
            innerAudioContext.onPlay(() => { });//播放音效
            innerAudioContext.onError((res) => {//打印错误
              console.log(res.errMsg);//错误信息
              console.log(res.errCode);//错误码
            })
            // innerAudioContext.play();
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })
            that.setData({
              msgList,
              content: json.answer,
              flag: " "

            })

            that.wordYun()

          },

          fail: function (ress) {
            console.log("。。录音保存失败。。");
          }
        })
      }
    })
    // })
  },




  //录音播放
  recordingAndPlaying: function (eve) {
    wx.playBackgroundAudio({
      //播放地址
      dataUrl: '' + eve.currentTarget.dataset.gid + ''
    })
  },
  conInput: function (e) {
    this.setData({
      content: e.detail.value,
    })
  },




  // 文字转语音
  wordYun: function () {
    var that = this;
    var content = that.data.content;
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: content,
      success: function (res) {
        console.log(res);
        console.log("succ tts", res.filename);
        that.setData({
          src: res.filename
        })
        that.yuyinPlay();
      },
      fail: function (res) {
        console.log("fail tts", res)
      }
    })
  },

  //播放语音
  yuyinPlay: function (e) {
    if (this.data.src == '') {
      console.log(暂无语音);
      return;
    }
    this.innerAudioContext.src = this.data.src //设置音频地址
    this.innerAudioContext.play(); //播放音频
  },

  end: function (e) {
    this.innerAudioContext.pause();//暂停音频
  },
  //点击查询
  handSeir(e) {
    var thar = this;
    console.log(e.currentTarget.dataset.key)
    if (e.currentTarget.dataset.key == "织布鸟项目组张帆" || e.currentTarget.dataset.key == "蜂巢项目组张雪晨" || e.currentTarget.dataset.key == "探路者项目组麻树强" || e.currentTarget.dataset.key == "办公室李洋") {

      wx.request({
        url: 'https://gdzc.sxpmg.com/shuhai/wx_Putname.do',
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          name: e.currentTarget.dataset.key,
        },
        success: function (res) {
          console.log("_____________" + res.data);
          const innerAudioContext = wx.createInnerAudioContext();
          innerAudioContext.autoplay = true;
          innerAudioContext.src = "/audio/9675.mp3"
          innerAudioContext.onPlay(() => { });//播放音效
          innerAudioContext.onError((res) => {//打印错误
            console.log(res.errMsg);//错误信息
            console.log(res.errCode);//错误码
          })


          msgList.push({
            speaker: 'customer',
            contentType: 'text',
            content: e.currentTarget.dataset.key,
          });
          if (Object.keys(res.data).length === 0) {
            msgList.push({
              speaker: 'server',
              contentType: 'text',
              content: '你好该人员没有录入汇报内容',
              comtlost: res.data,
            });
          } else {
            msgList.push({
              speaker: 'server',
              contentType: 'text',
              content: '您可以这样提问？',
              comtlost: res.data,
            });
          }
          thar.setData({
            msgList,
          })
        }
      })
    } else {
      wx.request({
        url: 'https://gdzc.sxpmg.com/shuhai/wx_Putname.do',
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          name: e.currentTarget.dataset.key,
        },
        success: function (res) {
          console.log(">>>>>>>>>>>>>>>>>>>>" + res);
          console.log(">>>>>>>>>>>>>>>>>>>>" + res.data.answer)
          msgList.push({
            speaker: 'customer',
            contentType: 'text',
            content: res.data.hp,
          });
          msgList.push({
            speaker: 'server',
            contentType: 'text',
            content: res.data.answer,
          });
          const innerAudioContext = wx.createInnerAudioContext();
          innerAudioContext.autoplay = true;
          innerAudioContext.src = "/audio/9675.mp3"
          innerAudioContext.onPlay(() => { });//播放音效
          innerAudioContext.onError((res) => {//打印错误
            console.log(res.errMsg);//错误信息
            console.log(res.errCode);//错误码
          })
          thar.setData({
            msgList,
          })
        }
      })
    }

  },



})



